package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.logging.log4j.util.PropertySource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    /*
    * 分类数据修改同时修改表数据
    * */
    @Override
    public void updateCascade(CategoryEntity category) {

        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        long l1 = System.currentTimeMillis();
//        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
//        //找出所有的一级分类
//        Map<Long, List<CategoryEntity>> longListNavigableMap = categoryEntities.stream().collect(Collectors.groupingBy(CategoryEntity::getParentCid));
//
//        List<CategoryEntity> collect = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
//                .peek(menu -> menu.setChildren(getChildless(menu, categoryEntities)))
//                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
//                .collect(Collectors.toList());


        List<CategoryEntity> entities = new ArrayList<>(baseMapper.selectList(Wrappers.<CategoryEntity>lambdaQuery().orderByDesc(CategoryEntity::getCatId)));
        Map<Long, List<CategoryEntity>> longListNavigableMap = entities.stream().collect(Collectors.groupingBy(CategoryEntity::getParentCid));

        List<CategoryEntity> collect = entities.stream()
                .peek(entity -> {
            if (longListNavigableMap.containsKey(entity.getCatId())) {
                entity.setChildren(longListNavigableMap.get(entity.getCatId()));
            }
        })
                .filter(entity -> entity.getCatLevel() == 1)
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());





        long l2 = System.currentTimeMillis();
//        执行时间为551秒
        System.out.println("执行时间为" + (l2-l1)+"秒");
        return collect;
    }

    /*
    * 删除逻辑
    * */
    @Override
    public void removeMenuByIds(List<Long> asList) {


    }

    /*
    * 查找完整路径
    * */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
       List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
       return parentPath.toArray(new Long[parentPath.size()]);
    }



    /*
    * 递归查找父节点
    * */
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid()!=0){
            findParentPath( byId.getParentCid(),  paths);
        }
        paths.add(catelogId);
        return paths;
    }

    /*
    * 递归查找子菜单
    * */
    private List<CategoryEntity> getChildless(CategoryEntity root,List<CategoryEntity> all){
        return all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .peek(categoryEntity -> {
                    //找到子菜单
                    categoryEntity.setChildren(getChildless(categoryEntity,all));
                })
                .sorted(Comparator.comparingInt(menu->(menu.getSort()==null?0: menu.getSort())))
                .collect(Collectors.toList());
    }

}